﻿using System;
using System.Windows;
using System.Windows.Controls;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using IssueVision.Common;
using MVVMPlugin;

namespace IssueVision.Client
{
    [ExportPlugin(ViewTypes.AllIssuesView, PluginType.View)]
    public partial class AllIssues : UserControl, ICleanup
    {
        #region "Private Data Members"
        private const double MinimumWidth = 640;
        #endregion "Private Data Members"

        #region "Constructor"
        public AllIssues()
        {
            InitializeComponent();
            // add the IssueEditor
            issueEditorContentControl.Content = new IssueEditor();
            // initialize the UserControl Width & Height
            Content_Resized(this, null);

            // register any AppMessages here

            if (!ViewModelBase.IsInDesignModeStatic)
            {
                // set DataContext
                DataContext = PluginCatalogService.Instance.FindPlugin(
                    ViewModelTypes.AllIssuesViewModel, PluginType.ViewModel);
            }
        }
        #endregion "Constructor"

        #region "Logic to dynamically set UserControl Width and Height"

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Application.Current.Host.Content.Resized += Content_Resized;
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            Application.Current.Host.Content.Resized -= Content_Resized;
        }

        private void Content_Resized(object sender, EventArgs e)
        {
            // stretch the UserControl to the current browser width if wider than MinimumWidth
            if (Application.Current.Host.Content.ActualWidth < MinimumWidth)
                Width = MinimumWidth;
            else
                Width = Application.Current.Host.Content.ActualWidth;
            // stretch the UserControl to the current brower Height - Title Height(42) - Menu Height(22)
            Height = Application.Current.Host.Content.ActualHeight - 42 - 22;
        }

        #endregion "Logic to dynamically set UserControl Width and Height"

        #region "ICleanup interface implementation"

        public void Cleanup()
        {
            // call Cleanup on its ViewModel
            ((ICleanup)DataContext).Cleanup();
            // call Cleanup on IssueEditor
            var issueEditor = issueEditorContentControl.Content as ICleanup;
            if (issueEditor != null)
                issueEditor.Cleanup();
            issueEditorContentControl.Content = null;
            // cleanup itself
            Messenger.Default.Unregister(this);
            // call ReleasePlugin on its ViewModel
            PluginCatalogService.Instance.ReleasePlugin(DataContext);
            DataContext = null;
        }

        #endregion "ICleanup interface implementation"
    }
}
